package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hmdp.utils.RedisConstants.SHOP_TYPE_LIST;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        String key = SHOP_TYPE_LIST;
//        1. 根据商品id去redis中查询数据
        String list = stringRedisTemplate.opsForValue().get(key);
//        2. 存在直接返回
        if (!StrUtil.isBlankIfStr(list)) {
            List<ShopType> shop = JSONUtil.toList(list, ShopType.class);
            return Result.ok(shop);
        }
//        3. 不存在去数据查询
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
//        4. 判断数据库中是否有数据
        if (null == shopTypeList) {
//        5. 没有直接返回错误信息
            return Result.fail("店铺不存在");
        }
//        6. 存在返回数据并且将数据存入redis中
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypeList));

        return Result.ok(shopTypeList);
    }
}
